<template>
  <inline-Modal
    :visible="visible"
    title="例会文件管理"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="loading"
      @click="handelOk()"
    >
      确定
    </a-button>
    <div class="files-page-container">
      <div class="sub-title">
        港口控股集团工程建设月度例会汇报（
        {{ formatDate(parameter.monthData) }}
        ）
      </div>
      <div class="table-container">
        <vxe-table
          border
          :data="lastTableData"
          size="small"
          min-height="100%"
          align="center"
        >
          <vxe-colgroup title="一、上月交办事项完成情况">
            <vxe-column width="80" title="序号">
              <template #default="{ row }">
                <a-input v-model="row.sort"></a-input>
              </template>
            </vxe-column>
            <vxe-column
              field="assigningUnitsDesc"
              title="交办单位"
              width="170px"
            ></vxe-column>
            <vxe-column
              field="cooperateUnitsDesc"
              title="配合单位"
              width="180px"
            ></vxe-column>
            <vxe-column
              field="tasks"
              title="交办事项"
              width="400px"
            ></vxe-column>
            <vxe-column field="completionStatus" title="完成情况">
              <template #default="{ row }">
                <div v-if="row.completionStatus">
                  {{ row.completionStatus }}
                </div>
                <div v-else class="error">（未完成）</div>
              </template>
            </vxe-column>
          </vxe-colgroup>
        </vxe-table>
      </div>
      <div class="table-container">
        <vxe-table
          border
          :data="currentTableData"
          size="small"
          min-height="100%"
          align="center"
          :span-method="mergeRowMethod"
        >
          <vxe-colgroup title="二、本月重点工程进展">
            <vxe-column field="workAreaDesc" title="所属区域"></vxe-column>
            <vxe-column width="80" title="序号">
              <template #default="{ row }">
                <a-input v-model="row.monthSort"></a-input>
              </template>
            </vxe-column>
            <vxe-column field="projecUnit" title="项目单位"></vxe-column>
            <vxe-column field="proName" title="项目名称"></vxe-column>
            <vxe-column
              field="progressAndCompletion"
              title="形象进度及完成情况(重要节点工期)"
            ></vxe-column>
            <vxe-column
              field="yearPlanInvestment"
              title="投资情况(万元)"
            ></vxe-column>
            <vxe-column
              field="planActualComparison"
              :title="
                lastMonth(parameter.monthData) + '月份项目计划与实际完成对比'
              "
            ></vxe-column>
            <vxe-column
              field="schedule"
              :title="calcMonths(parameter.monthData, 1) + '月份进度计划'"
            ></vxe-column>
            <vxe-column field="progressSelfAssessment" title="进度自评">
              <template #default="{ row }">
                <div v-if="row.laggingBehind == 0">
                  <div>序时推进</div>
                  <div v-if="row.progressSelfAssessment">
                    （{{ row.progressSelfAssessment }}）
                  </div>
                </div>
                <div v-else class="error">
                  <div>进度滞后</div>
                  <div v-if="row.progressSelfAssessment">
                    （{{ row.progressSelfAssessment }}）
                  </div>
                </div>
              </template>
            </vxe-column>
          </vxe-colgroup>
        </vxe-table>
      </div>
    </div>
  </inline-Modal>
</template>

<script>
import { getMeetingFileByMonth, saveSortData } from "@/api/safetyManage";
export default {
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      //本月
      currentTableData: [],
      //上月
      lastTableData: [],
    };
  },
  computed: {},
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getData() {
      return new Promise((resolve, reject) => {
        let { monthData } = this.parameter;
        getMeetingFileByMonth({ monthData })
          .then((res) => {
            let { data } = res;
            this.currentTableData = data?.currentMonthData ?? [];
            this.lastTableData = data?.preMonthData ?? [];
            resolve();
          })
          .catch((_) => {
            this.currentTableData = [];
            this.lastTableData = [];
            reject();
          });
      });
    },

    handelOk() {
      let { currentTableData, lastTableData } = this;
      let formJson = {
        preMonthData: [],
        currentMonthData: [],
      };
      lastTableData.forEach((v) => {
        formJson.preMonthData.push({
          uuid: v.uuid,
          sort: v?.sort ?? "",
        });
      });
      currentTableData.forEach((v) => {
        formJson.currentMonthData.push({
          uuid: v.uuid,
          monthSort: v?.monthSort ?? "",
        });
      });
      this.loading = true;
      saveSortData(formJson)
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.handelCancel();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {})
        .finally((_) => {
          this.loading = false;
        });
    },

    handelCancel() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },

    //日期转换
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "long",
      });
    },

    // 通用行合并函数（将相同多列数据合并为一行）
    mergeRowMethod({ row, _rowIndex, column, visibleData }) {
      const fields = ["workAreaDesc"];
      const cellValue = row[column.field];
      if (cellValue && fields.includes(column.field)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.field] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.field] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },

    lastMonth(time) {
      let last = this.calcMonths(time, -1);
      let next = this.calcMonths(time, 1);
      return last + "-" + (next - 1);
    },
    calcMonths(time, num) {
      if (!time) {
        return;
      }
      let arr = time.split("-"); // 将 "yyyy-MM" 日期分解为 ["2021","09"]
      let year = parseInt(arr[0], 10);
      let month = parseInt(arr[1], 10);
      month = month + num;
      if (month > 12) {
        let newYear = parseInt((month - 1) / 12, 10);
        month = month % 12 == 0 ? 12 : month % 12;
        year += newYear;
      } else if (month <= 0) {
        month = Math.abs(month);
        let newYear = parseInt((month + 12) / 12, 10);
        let n = month % 12;
        if (n == 0) {
          year -= newYear;
          month = 12;
        } else {
          year -= newYear;
          month = Math.abs(12 - n);
        }
      }
      //   month = month < 10 ? "0" + month : month;
      //   return year + "-" + month;
      return month;
    },
  },
};
</script>

<style lang="less" scoped>
.add-btn {
  position: absolute;
  top: 10px;
  right: 90px;
}
.files-page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
  padding: 0 20px;
  box-sizing: border-box;
  .sub-title {
    padding: 10px 0 20px 0;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 18px;
    color: #333333;
    letter-spacing: 1px;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
  .table-container {
    flex: 1;
    /deep/.vxe-table {
      .vxe-table--header-wrapper {
        table {
          thead {
            .vxe-header--row:nth-child(1) {
              background: rgba(22, 119, 255, 0.05);
              font-family: Microsoft YaHei, Microsoft YaHei;
              font-weight: bold;
              font-size: 14px;
              color: #333333;
            }
          }
        }
      }
      .vxe-table--body-wrapper {
        table {
          .vxe-body--row {
            .vxe-body--column {
              border-bottom: 1px solid rgba(217, 217, 217, 0.8);
            }
          }
        }
      }
    }
    .error {
      color: #ff2d2d;
    }
  }
}
</style>
